﻿using ApplicationModels.A07.Chats;
using AutoMapper;
using Commons.Responses;
using DomainCommons.Models;
using EntityModels.E02.Identities;
using EntityModels.E07.Chats;
using IApplicationServices;
using IRepositories;

namespace ApplicationService
{
    public class ConversationService:BaseApplicationService<int,Conversation,ConversationAM>, IConversationService
    {
        public ConversationService(IBaseRepository<int, Conversation> repository, IMapper mapper) : base(repository, mapper)
        {
        }
        /// <summary>
        /// 添加新的会话
        /// </summary>
        /// <param name="apiBo"></param>
        /// <returns></returns>
        public override async Task<MessageResponse> AddAsync(ConversationAM apiBo)
        {
            try
            {
                var conver = await Repository.GetAsync(x => x.ParticipantIds.Any(y => y == apiBo.SenderId) && x.ParticipantIds.Any(y => y == apiBo.ReceiverId));
                if (conver == null)
                {
                    apiBo.ParticipantIds.Add(apiBo.SenderId);
                    apiBo.ParticipantIds.Add(apiBo.ReceiverId);
                    apiBo.DisplayIds = apiBo.ParticipantIds;
                    var bo = Mapper.Map< Conversation>(apiBo);
                    var res =  await Repository.AddAsync(bo);
                    return new MessageResponse(res.Data.Id.ToString(), res.Successed);
                }
                //不对用户隐藏这条对话
                apiBo.DisplayIds.Add(apiBo.SenderId);
                return new MessageResponse(conver.Id.ToString(), true);
            }catch(Exception e)
            {
                return null;
            }

        }

        public async Task<DatasResponse<ConversationAM>> GetConversations(string userId)
        {
            var converRes = await Repository.GetAllAsync(x => x.ParticipantIds.Any(y => y == userId) && x.DisplayIds.Any(y => y == userId),new Dictionary<string, bool> { { "LastUpdated",true } });
            var am = Mapper.Map<List<ConversationAM>>(converRes.Datas);

            foreach (var item in am)
            {
                var receiverId = item.ParticipantIds.FirstOrDefault(x => x != userId);
                var receiver = (await Repository.GetOtherByIdAsync<Guid, AppUser>(Guid.Parse(receiverId))).Data;
                item.ReceiverName = receiver.NickName;
                item.ReceiverAvatar = receiver.Avatar.ToString();
            }
            return new DatasResponse<ConversationAM>(converRes.Total, am);
        }


    }
}
